package com.neeraj.SharingArtifacts;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class VisitPlaces extends Activity {
	
	private static final String DEBUG_TAG = "Visit Places";
	private static final String IP_ADDRESS = "192.168.1.67";
//	private static final String IP_ADDRESS = "pba.cs.clemson.edu/~neerajj";
	EditText searchText;
	Button searchButton;
	ListView listviewResult;
	Bundle bun;
	 
	Geocoder myGeocoder;
	final static int MAX_RESULT = 10;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_options);
	    	          
        searchText = (EditText)findViewById(R.id.searchtext);
        searchText.setText("");
        searchButton = (Button)findViewById(R.id.visitbutton);
        listviewResult = (ListView)findViewById(R.id.listviewresult);
        listviewResult.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int pos, long id) {
				// TODO Auto-generated method stub
        		
        		Address add = (Address) listviewResult.getAdapter().getItem(pos);
        		String addinfo = add.getAddressLine(0);
        		double lat = add.getLatitude();
        		double lon = add.getLongitude();
        		Log.i(DEBUG_TAG, "lat: "+lat+", lon: "+lon);
        		String urlString = "http://"+ IP_ADDRESS +"/sharingArtSelect.php";
    			
        		String result = "";
        		
        		MultipartEntity reqEntity = new MultipartEntity();
    			HttpClient client = new DefaultHttpClient();
    	    	HttpPost post = new HttpPost(urlString);
    			try {
					reqEntity.addPart("latitude", new StringBody(Double.toString(lat)));
					reqEntity.addPart("longitude", new StringBody(Double.toString(lon)));
					post.setEntity(reqEntity);
	    			HttpResponse response = client.execute(post);
	    			HttpEntity entity = response.getEntity();
	                InputStream is = entity.getContent();

	                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
	                StringBuilder sb = new StringBuilder();
	                String line = null;
	                while ((line = reader.readLine()) != null) {
	                	Log.i(DEBUG_TAG, "m i entering in here! " + line);
	                        sb.append(line + "\n");
	                }
	                is.close();
	         
	                result=sb.toString();
	                StringBuilder sbnull = new StringBuilder();
	                Log.i(DEBUG_TAG, "is it have an enter" + " " + sbnull.toString().equals(result));
	                Log.i(DEBUG_TAG, "result b4 ifff" + result + result.length());
	                if(result.length() == 3 )
	                	Log.i(DEBUG_TAG, "No data found!");
				} catch (Exception e) {
					e.printStackTrace();
				}
    			    			    			        		
        		Toast.makeText(getApplicationContext(), addinfo, Toast.LENGTH_SHORT).show();        		        	
        		Log.i(DEBUG_TAG, "let c what is there in result: " + result);
        		Intent passInfo = new Intent(VisitPlaces.this, CustomMap.class);
				
				Bundle infoToPass = new Bundle();
				infoToPass.putString("json", result);
				infoToPass.putDouble("latitude", lat);
				infoToPass.putDouble("longitude", lon);
				passInfo.putExtras(infoToPass);
				Log.i(DEBUG_TAG, "Everything fine so far!!!");
				startActivityForResult(passInfo, 0);
				
			}
		});
     
        searchButton.setOnClickListener(searchButtonOnClickListener);       
     
        myGeocoder = new Geocoder(this);
        //for API Level 9 or higher
        if (!Geocoder.isPresent()){
        	Toast.makeText(getBaseContext(),
        	"Sorry! Geocoder service not Present.",
        	Toast.LENGTH_LONG).show();
        }
     
//     searchFromLocationName(loc);
    }
    
    Button.OnClickListener searchButtonOnClickListener = new Button.OnClickListener(){ 
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    	if(v.getId() == R.id.visitbutton) {
    		String searchString = searchText.getText().toString();
    		searchFromLocationName(searchString);
    	}
    }};
   
    private void searchFromLocationName(String name){
    	try {
    		List<Address> result
    		= myGeocoder.getFromLocationName(name, MAX_RESULT);
    
    		if ((result == null)||(result.isEmpty())){
    			Toast.makeText(getBaseContext(),
    					"No matches were found or there is no backend service!",
    					Toast.LENGTH_LONG).show();
    		}else{
    			MyArrayAdapter adapter = new MyArrayAdapter(this, android.R.layout.simple_list_item_1, result);
    			listviewResult.setAdapter(adapter);
     
    			Toast.makeText(getBaseContext(), "Finished!", Toast.LENGTH_SHORT).show();
    		}
    	} catch (IOException e) {
    // TODO Auto-generated catch block
    		e.printStackTrace();
    		Toast.makeText(getBaseContext(),
    				"The network is unavailable or any other I/O problem occurs!",
    				Toast.LENGTH_LONG).show();
    	}
    }
  
  public static boolean isNotNullNotEmptyNotWhiteSpaceOnly(final String string) {
	  return string != null && !string.isEmpty() && !string.trim().isEmpty();
  }
   
  public class MyArrayAdapter extends ArrayAdapter<Address> {
	  Context mycontext;
	  public MyArrayAdapter(Context context, int textViewResourceId,
			  List<Address> objects) {
		  super(context, textViewResourceId, objects);
    // TODO Auto-generated constructor stub
		  mycontext = context;
	  }
   
   @Override
   	public View getView(int position, View convertView, ViewGroup parent) {
	   // TODO Auto-generated method stub
    
	   int maxAddressLineIndex = getItem(position).getMaxAddressLineIndex();
	   String addressLine = "";
    
	   for (int j = 0; j <= maxAddressLineIndex; j++){
		   addressLine += getItem(position).getAddressLine(j) + ",";
	   }
    
	   TextView rowAddress = new TextView(mycontext);
	   rowAddress.setText(addressLine);
    
	   return rowAddress;
   
   	}
   
  }
}